<template>
	<view class="e-select" :class="[ns.is('disabled',elDisabled)]" :style="[show?{zIndex:props.zIndex}:{}]">
		<view class="e-select__mask" @click="handleClick">
			
		</view>
		<e-input :customStyle="customStyle" :modelValue="inputText" :placeholder="props.placeholder"
			:placeholderClass="props.placeholderClass" :placeholderStyle="props.placeholderStyle"
			:disabledColor="props.disabledColor" :border="props.border" :shape="props.shape" readonly
			>
			<template v-slot:prefix v-if="$slots.prefix">
				<slot name="prefix">

				</slot>
			</template>
			<template v-slot:suffix>
				<slot name="suffix">
					<e-icon name="arrow-down" size="18"></e-icon>
				</slot>
			</template>
		</e-input>
		<transition-box :show="show" >
			<view class="e-select__option" :style="[scrollStyle]">
				<scroll-view class="e-select__option-scroll" :style="[{height: addUnit(scrollHeight)}]" scroll-y="true">
					<slot>
					</slot>
				</scroll-view>
			</view>
		</transition-box>
	</view>
</template>

<script lang="ts">
	import {defineComponent} from 'vue'
	import mpMixin from "../../libs/mixin/mpMixin";
	/**
	 * select 选择器
	 * @description 选择器
	 * @tutorial https://www.uviewui.com/components/select.html
	 * @property {String | Number| Boolean}	modelValue					输入的值
	 * @property {Boolean}			disabled				是否禁用 （ 默认 false ）
	 * @property {String}			disabledColor			禁用状态时的背景色（ 默认 '#f5f7fa' ）
	 * @property {String}			placeholder				输入框为空时的占位符
	 * @property {String}			placeholderClass		指定placeholder的样式类，注意页面或组件的style中写了scoped时，需要在类名前写.deep （ 默认 'input-placeholder' ）
	 * @property {String | Object}	placeholderStyle		指定placeholder的样式，字符串/对象形式，如"color: red;"
	 * @property {String}			inputAlign				输入框内容对齐方式（ 默认 'left' ）
	 * @property {String}			prefixIcon				输入框前置图标
	 * @property {String | Object}	prefixIconStyle			前置图标样式，对象或字符串
	 * @property {String}			suffixIcon				输入框后置图标
	 * @property {String | Object}	suffixIconStyle			后置图标样式，对象或字符串
	 * @property {String}			border					边框类型，surround-四周边框，bottom-底部边框，none-无边框 （ 默认 'surround' ）
	 * @property {Boolean}			readonly				是否只读，与disabled不同之处在于disabled会置灰组件，而readonly则不会 （ 默认 false ）
	 * @property {String}			shape					输入框形状，circle-圆形，square-方形 （ 默认 'square' ）
	 * @property {Object}			customStyle				定义需要用到的外部样式
	 * @event {Function} update:modelValue 绑定值改变
	 * @event {Function} change 绑定值改变
	 * @example <e-select :show="show"><e-option>A选项</e-option></e-select>
	 */
	export default defineComponent({
		name: "e-select",
		mixins: [mpMixin],
	});
</script>

<script lang="ts" setup>
	import {
		ref,
		reactive,
		computed,
		watch,
		nextTick,
		provide,
		toRefs
	} from 'vue'
	import {
		selectProps,
		selectEmits
	} from "./props";
	import {
		useNamespace,
		useFormItem,
		useDisabled,
		useDefaultProps
	} from '../../libs/hooks'
	import {
		type SelectContext,
		type OptionContext,
		selectContextKey
	} from '../../libs/tokens'
	import {
		empty
	} from '../../libs/utils'
	import {
		addUnit
	} from '../../libs/utils/_utils'
	import componentsProps from "../../libs/config/componentsProps";
	import type {
		 SelectProps
	} from "../../libs/config/propsType";
	import transitionBox from './transition.vue'

	const {
		select: selectDefaultProps
	} = toRefs(componentsProps);

	const _props = defineProps(selectProps)

	const props = useDefaultProps < SelectProps > (_props, selectDefaultProps);
	const emit = defineEmits(selectEmits)

	const {
		form,
		formItem
	} = useFormItem()
	const ns = useNamespace('select')

	const elDisabled = useDisabled()

	const children= reactive<OptionContext[] >([])

	const addField: SelectContext['addField'] = (field) => {
		children.push(field)
		getInputText()
	}

	const removeField: SelectContext['removeField'] = (field) => {
		let index = children.indexOf(field)
		if (index > -1) {
			children.splice(index, 1)
			getInputText()
		}
	}

	const show = ref(false)
	const scrollHeight = computed(() => {
		return (children.length > props.value.showOptionNumber ? props.value.showOptionNumber : children.length)*(children[0]?.props?.height||0)
	})
	
	const scrollStyle = computed(() => {
		return {
			bottom:addUnit(10 - scrollHeight.value),
			height: addUnit(scrollHeight.value)
		}
	})
	
	const inputText = ref('')

	const getInputText = () => {
		if (!empty(props.value.modelValue)) {
			let option = children.find(item => props.value.modelValue === item.props.value)
			if (option) {
				inputText.value = `${option.props?.label||option.props?.value||props.value.modelValue}`
			} else {
				inputText.value = `${props.value.modelValue}`
			}
		}
	}

	const handleClick = () => {
		console.log(111)
		if (elDisabled.value) return
		show.value = !show.value
	}

	const optionChange = (field: OptionContext) => {
		let value =  field?.props.value || field?.props.label
		emit('change', value)
		emit('update:modelValue', value)
		show.value = false
		nextTick(() => {
			getInputText()
		})
	}



	watch(() => props.value.modelValue, () => {
		// 尝试调用e-form的验证方法，进行一定延迟，否则微信小程序更新可能会不及时
		nextTick(() => {
			// 如果checkbox-group是在form组件内，调用form组件的validateField
			if (formItem && form) {
				form.validateField([formItem.props.prop], () => {}, 'change')
			}
			getInputText()
		})
	})


	provide(selectContextKey, reactive({
		props,
		addField,
		removeField,
		optionChange
	}))
</script>

<style lang="scss" scoped>
	@import "../../libs/theme/select.scss";
</style>
